<?php
class EGoogleMap extends CWidget{

	public $gMapScript='http://maps.google.com/maps/api/js';

	public $sensor=false;

	public $region='AU';

	public $key;

	public $address;

	public $labelHtml;

	public $markerIcon;

	public $container;

	public $labelMaxWidth=199;


	public $containerOptions=array();

	public $defaultLat='-37.817677';

	public $defaultLng='144.967334';

	private $scriptCode;


	public function init()	{
		$url=$this->gMapScript.'?sensor='.($this->sensor?'true':'false')
		.'&region='.$this->region
		.'&key='.$this->key;
		Yii::app()->clientScript->registerScriptFile($url);
		$this->scriptCode=<<<EOF
  var map = new google.maps.Map(document.getElementById("{$this->container}"), {
    zoom: 15,
    mapTypeId: google.maps.MapTypeId.ROADMAP,
    center:  new google.maps.LatLng({$this->defaultLat},{$this->defaultLng})
  });
EOF;
	}



	public function run()	{

		if($this->address){
			$addressOption=CJavaScript::encode(array('address'=>$this->address));
			$labelScript='';
			if($this->labelHtml){
				$labelOptions=CJavaScript::encode(array('content'=>$this->labelHtml,
				'maxWidth'=>$this->labelMaxWidth));
				$labelScript=<<<EOF
			var infowindow = new google.maps.InfoWindow($labelOptions);
		google.maps.event.addListener(marker, 'click', function() {
			infowindow.open(map,marker);
		});
		infowindow.open(map,marker);
EOF;
			}
			$markerOptions=array('map'=>'js:map','position'=>'js:results[0].geometry.location');
			if($this->markerIcon){
				$markerOptions['icon']=$this->markerIcon;
			}
			$markerOptions=CJavaScript::encode($markerOptions);
			$this->scriptCode.=<<<EOF
geocoder = new google.maps.Geocoder();
geocoder.geocode( $addressOption , function(results, status) {
	if (status == google.maps.GeocoderStatus.OK) {
		map.setCenter(results[0].geometry.location);
		var marker = new google.maps.Marker($markerOptions);
		$labelScript
        } else {
          //alert("Geocode was not successful for the following reason: " + status);
          //hide map
          $('{$this->container}').css('display','none');
        }
      });
      
EOF;
		}

		Yii::app()->clientScript->registerScript($this->getId().'_'.$this->container,$this->scriptCode);
		$this->containerOptions['id']=$this->container;
		echo CHtml::tag('div',$this->containerOptions,'');
	}

}